package com.lmy.springCloud.service.Impl;

import com.lmy.springCloud.dao.OrderDao;
import com.lmy.springCloud.entity.Order;
import com.lmy.springCloud.service.AccountOpenFeignService;
import com.lmy.springCloud.service.OrderService;
import com.lmy.springCloud.service.StorageOpenFeignService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private AccountOpenFeignService accountOpenFeignService;

    @Resource
    private StorageOpenFeignService storageOpenFeignService;

    @Resource
    private OrderDao orderDao;

    /**
     * 1.@GlobalTransactional 表示分布式全局事务控制 io.seata.spring.annotation
     * 2.name="lmy-save-order" 名称，自己指定，保证唯一即可
     * 3.rollbackFor = Exception.class 指定发生什么异常就回滚，
     *   这里指定了Exception，即只要发生了异常就回滚
     * 4.分布式全局事务超时时间为60s
     * @param order 订单对象
     */
    @Override
    @GlobalTransactional(name="lmy-save-order",
            rollbackFor = Exception.class)
    public void save(Order order) {

        log.info("==============创建订单start===============");

        //1. 调用本地方法新增订单
        log.info("==============本地生成订单start=============");
        orderDao.save(order);
        log.info("==============本地生成订单end=============");

        //2. 远程调用方法扣减库存
        log.info("==============扣减库存start=============");
        storageOpenFeignService.reduce(order.getProductId(), order.getNums());
        log.info("==============扣减库存end=============");

        //3. 远程调用方法扣减账户金额
        log.info("==============扣减账户金额start=============");
        accountOpenFeignService.reduce(order.getUserId(), order.getMoney());
        log.info("==============扣减账户金额end=============");

        //4. 调用本地方法修改订单状态为已完成
        log.info("==============修改订单状态start=============");
        orderDao.update(order.getUserId(), 1);
        log.info("==============修改订单状态end=============");

        log.info("==============创建订单end===============");
    }
}
